/*
   Copyright (c) 2023 李伟国
   learner-platform is licensed under Mulan PSL v2.
   You can use this software according to the terms and conditions of the Mulan PSL v2. 
   You may obtain a copy of Mulan PSL v2 at:
               http://license.coscl.org.cn/MulanPSL2 
   THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.  
   See the Mulan PSL v2 for more details. 
*/

package cn.platform.service.impl;

import cn.platform.config.properties.ConfigUploadProperties;
import cn.platform.service.IFileService;
import org.apache.shiro.authc.AuthenticationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
public class FileServiceImpl implements IFileService {
    private final static Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);
    @Autowired
    private ConfigUploadProperties uploadProperties;

    @Override
    public String getImagePath() {
        return uploadProperties.getImagePath();
    }

    @Override
    public String saveImageFile(MultipartFile file) {
        if(file == null){
            return null;
        }
        File dir = new File(uploadProperties.getImagePath());
        if(!dir.exists()){
            boolean mkdirs = dir.mkdirs();
        }
        if(file.getOriginalFilename() == null){
            // TODO 文件名为空异常
            throw new AuthenticationException("文件名为空");
        }
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
        String filename = UUID.randomUUID()+suffix;
        filename = filename.replaceAll("\\s+", "").replace("-","");
        File dest = new File(uploadProperties.getImagePath()+File.separator+filename);
        try{
            file.transferTo(dest);
        }catch (IOException e){
            e.getStackTrace();
            logger.error("图片保存失败！");
        }
        return uploadProperties.getDomain()+"/file/image/"+filename;
    }

    @Override
    public String findFilePath(String filename) {
        File file = new File(uploadProperties.getImagePath()+File.separator+filename);
        if(!file.exists()){
            return null;
        }
        return file.getPath();
    }


}
